import { Form, Input, Button, Select, Space, message, Radio } from "antd";
import { useModel } from "umi";
import { useReactive } from "ahooks";
import { useEffect } from "react";
import { v4 as uuidv4 } from "uuid";
import { CreateMemberMessage, CheckConstraintMessages } from "../_graphql";
import { AllSuperior } from "./_graphql";

const { Option } = Select;

const layout = { labelCol: { span: 6 }, wrapperCol: { span: 16 } };
const tailLayout = { wrapperCol: { offset: 6, span: 16 } };

const RemovedRecertification = ({ record, reviewType }) => {
    const { remoteData } = useModel("global");
    const { baseInfo, memberInfo } = useModel("person.info");
    const { organizationUuid } = useModel("organization.info");
    const { applicationInfo } = useModel("application.info");
    const { onCloseGlobalModal } = useModel("global.modal");
    const { members, reviewerRoles } = useModel("members.info");
    const [form] = Form.useForm();

    const state = useReactive({
        innerMembers: [],
        omEouu: "",
        applyText: `【${baseInfo.realName}】申请把【${record.omName}】转为组织成员，请${reviewType}。`,
    });

    useEffect(() => {
        if (reviewType === "审核") {
            let reviewers = reviewerRoles["member_reviewer"].members;
            if (reviewers.length > 0) state.reviewers = reviewers.filter((item) => item.omUuid !== baseInfo.uuid && item.arLeve === 1);
            else {
                reviewers = members;
                state.reviewers = reviewers.filter((item) => item.omUuid !== baseInfo.uuid);
            }
        }
        if (reviewType === "审批") {
            loadSuperior();
        }
    }, [members, reviewerRoles]);

    const loadSuperior = async () => {
        let res = await graphqlFetch({
            query: AllSuperior,
            variables: {
                omUuid: memberInfo.omDisu,
            },
        });
        state.reviewers = res?.a?.nodes || [];
    };

    const onFinish = async (values) => {
        let res = await remoteData({
            object: "multi-organization-gateway",
            serviceName: "/graphql/public_graphql_service",
            organizationUuid,
            params: { query: CheckConstraintMessages, variables: { mmCstn: record.omUuid } },
        });
        if (res?.a?.totalCount === 0) {
            values.reason = values.reason ? values.reason.replace(/\s+/g, "") : "";
            const receiver = state.reviewers.find((item) => item.omUuid === values.omUuid);
            const variables = {
                //应用信息
                aiIcon: applicationInfo.aiIcon,
                aiName: applicationInfo.aiName,
                aiUuid: applicationInfo.aiUuid,
                //命令
                mmActs: [
                    { title: "去" + reviewType, path: "messages/recertification", params: { omUuid: record.omUuid, omIfim: values.omIfim }, winOptions: {} },
                ],
                mmCrti: new Date().getUTCTime(),
                mmFomt: "text",
                mmLevl: 1,
                //接收人
                mmReav: receiver.omAvta,
                mmReer: receiver.omName,
                mmReid: receiver.omUuid,
                //场景
                mmScen: "移除人员转组织成员",
                //发送人
                mmSdav: memberInfo.omAvta,
                mmSder: memberInfo.omName,
                mmSdid: memberInfo.omUuid,
                mmSdpt: memberInfo.omPosi,
                //内容和类型
                mmText: state.applyText.replace("组织成员", values.omIfim ? "组织内部成员" : "组织外部成员") + `申请原由: ${values.reason || "无"}`,
                mmType: reviewType,
                mmUuid: uuidv4(),
                mmCstn: record.omUuid, // 应用场景约束值，防止重复
            };
            let res = await remoteData({
                object: "multi-organization-gateway",
                serviceName: "/graphql/public_graphql_service",
                organizationUuid,
                params: { query: CreateMemberMessage, variables },
            });
            if (res) {
                message.success("成功提交申请");
                onCloseGlobalModal();
            }
        } else {
            message.warn("已经有其它相关业务在等待处理，不能提交本次业务的申请！！！");
        }
    };

    const reviewerValidater = (rule, value) => {
        if (value) {
            if (state.reviewers.length === 1) return Promise.resolve();
            if (value === baseInfo.uuid) return Promise.reject("审核人员不能选择自己");
            else return Promise.resolve();
        } else {
            return Promise.reject("选择" + reviewType + "人员");
        }
    };

    return (
        <Form {...layout} form={form} onFinish={onFinish}>
            <Form.Item label="申请内容">{state.applyText}</Form.Item>

            <Form.Item name="omIfim" label="成员类型" rules={[{ required: true, message: "请选择成员类型" }]}>
                <Radio.Group>
                    <Radio value={true}>内部成员</Radio>
                    <Radio value={false}>外部成员</Radio>
                </Radio.Group>
            </Form.Item>

            <Form.Item name="omUuid" label={"选择" + reviewType + "人员"} rules={[{ required: true, validator: reviewerValidater }]}>
                <Select allowClear>
                    {state.reviewers?.map((item) => (
                        <Option key={item.omUuid} value={item.omUuid}>
                            {item.omName} {item.omPosi ? " - " + item.omPosi : ""}
                        </Option>
                    ))}
                </Select>
            </Form.Item>

            <Form.Item name="reason" label="申请原由">
                <Input />
            </Form.Item>

            <Form.Item {...tailLayout}>
                <Space>
                    <Button type="primary" htmlType="submit">
                        提交申请
                    </Button>
                    <Button htmlType="button" onClick={() => form.resetFields()}>
                        重置
                    </Button>
                </Space>
            </Form.Item>
        </Form>
    );
};

export default RemovedRecertification;
